package com.example.cardgame

import android.Manifest.permission.CAMERA
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.provider.MediaStore
import android.text.Editable
import android.text.TextUtils
import android.util.Base64
import android.util.Log
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.io.ByteArrayOutputStream

class UpdateActivity : AppCompatActivity() {
    companion object {
        const val REQUEST_IMAGE_CAPTURE = 1
    }

    private var imageBitmap: Bitmap? = null  //存储拍照结果



    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_update)

        // 获取控件
        val save: Button = findViewById(R.id.save)
        val cancel: Button = findViewById(R.id.cancel)
        val name: EditText = findViewById(R.id.name)
        val stuid: EditText = findViewById(R.id.stuid)
        val phonenumber: EditText = findViewById(R.id.phonenumber)
        val email: EditText = findViewById(R.id.email)
        val radioGroup: RadioGroup = findViewById(R.id.radioGroup)
        val gamecheck: CheckBox = findViewById(R.id.game)
        val tripcheck: CheckBox = findViewById(R.id.trip)
        val readcheck: CheckBox = findViewById(R.id.read)
        val shopcheck: CheckBox = findViewById(R.id.shopping)

        // 接收传递过来的参数
        val intent = getIntent()
        initializeFields(intent, name, stuid, phonenumber, email, radioGroup, gamecheck, tripcheck, readcheck, shopcheck)

        // 设置保存按钮点击事件
        save.setOnClickListener setOnClickListeners@{
            // 验证手机号是否合法
            val phone = phonenumber.text.toString()
            if (!isMobileNo(phone)) {
                Toast.makeText(this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show()
                return@setOnClickListeners
            }
            // 验证邮箱是否合法
            val tempemail = email.text.toString()
            if (!isValidEmail(tempemail)) {
                Toast.makeText(this, "请输入正确的邮箱地址", Toast.LENGTH_SHORT).show()
                return@setOnClickListeners
            }
            saveUserData(name, stuid, phonenumber, email, radioGroup, gamecheck, tripcheck, readcheck, shopcheck)
        }

        // 设置取消按钮点击事件
        cancel.setOnClickListener {
            finish()
        }

        // 拍照按钮
        val takePhoto: ImageButton = findViewById(R.id.takephoto)
        takePhoto.setOnClickListener {
            dispatchTakePictureIntent()
        }
    }

    // 初始化控件
    private fun initializeFields(intent: Intent, name: EditText, stuid: EditText, phonenumber: EditText, email: EditText, radioGroup: RadioGroup, gamecheck: CheckBox, tripcheck: CheckBox, readcheck: CheckBox, shopcheck: CheckBox) {
        name.text = Editable.Factory.getInstance().newEditable(intent.getStringExtra(NAME))
        stuid.text = Editable.Factory.getInstance().newEditable(intent.getStringExtra(STUID))
        phonenumber.text = Editable.Factory.getInstance().newEditable(intent.getStringExtra(PHONENUMBER))
        email.text = Editable.Factory.getInstance().newEditable(intent.getStringExtra(EMAIL))

        // 性别
        val gender = intent.getStringExtra(GENDER)
        radioGroup.check(if (gender == "女") R.id.woman else R.id.man)

        // 爱好
        val hobby = intent.getStringExtra(HOBBY)
        hobby?.split(",")?.forEach { h ->
            when (h) {
                "游戏" -> gamecheck.isChecked = true
                "旅游" -> tripcheck.isChecked = true
                "阅读" -> readcheck.isChecked = true
                "购物" -> shopcheck.isChecked = true
            }
        }

        // 照片
        val encodedImage = intent.getStringExtra("image")
        loadImage(encodedImage)
    }

    // 验证手机号
    private fun isMobileNo(mobiles: String): Boolean {
        val telRegex = "^1[345789]\\d{9}$"
        if(TextUtils.isEmpty(mobiles))
            return false
        else
            return mobiles.matches(telRegex.toRegex())
    }
    // 验证邮箱
    private fun isValidEmail(email: String): Boolean {
        val emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"
        if(TextUtils.isEmpty(email))
            return false
        else
            return email.matches(emailRegex.toRegex())
    }

    // 保存用户数据
    private fun saveUserData(name: EditText, stuid: EditText, phonenumber: EditText, email: EditText, radioGroup: RadioGroup, gamecheck: CheckBox, tripcheck: CheckBox, readcheck: CheckBox, shopcheck: CheckBox) {
        val intent = Intent()
        intent.putExtra(NAME, name.text.toString())
        intent.putExtra(STUID, stuid.text.toString())
        intent.putExtra(PHONENUMBER, phonenumber.text.toString())
        intent.putExtra(EMAIL, email.text.toString())

        // 性别
        val genderString = findViewById<RadioButton>(radioGroup.checkedRadioButtonId).text.toString()
        intent.putExtra(GENDER, genderString)

        // 爱好
        val hobbies = ArrayList<String>().apply {
            if (gamecheck.isChecked) add("游戏")
            if (tripcheck.isChecked) add("旅游")
            if (readcheck.isChecked) add("阅读")
            if (shopcheck.isChecked) add("购物")
        }
        intent.putExtra(HOBBY, hobbies.joinToString(","))

        // 图片
        imageBitmap?.let {
            val encodedImage = encodeImageToBase64(it)
            intent.putExtra("image", encodedImage)
        }

        setResult(RESULT_OK, intent)
        finish()
    }

    // 图片转换为Base64
    private fun encodeImageToBase64(image: Bitmap): String {
        ByteArrayOutputStream().use { stream ->
            image.compress(Bitmap.CompressFormat.PNG, 100, stream)
            return Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT)
        }
    }

    // 加载图片
    private fun loadImage(encodedImage: String?) {
        val imageView = findViewById<ImageView>(R.id.headsuit)
        if (encodedImage != null) {
            val byteArray = Base64.decode(encodedImage, Base64.DEFAULT)
            imageBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
            imageView.setImageBitmap(imageBitmap)
        } else {
            imageView.setImageResource(R.drawable.headsuit)
        }
    }

    // 拍照的方法
    private fun dispatchTakePictureIntent() {
        if (ContextCompat.checkSelfPermission(this, CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(CAMERA), REQUEST_IMAGE_CAPTURE)
        } else {
            Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
                if (takePictureIntent.resolveActivity(packageManager) != null) {
                    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
                } else {
                    Log.e("UpdateActivity", "No camera application found to handle the intent")
                }
            }
        }
    }

    // 处理拍照结束后的结果
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            val extras = data?.extras
            imageBitmap = extras?.get("data") as? Bitmap
            imageBitmap?.let {
                findViewById<ImageView>(R.id.headsuit).setImageBitmap(it)
            } ?: Log.e("UpdateActivity", "No image returned")
        }
    }

    // 处理权限请求结果
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_IMAGE_CAPTURE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                dispatchTakePictureIntent()
            } else {
                Toast.makeText(this, "相机权限被拒绝", Toast.LENGTH_SHORT).show()
            }
        }
    }
}
